<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\Setting;
use app\models\OrderInfo;
use app\models\OrderInfoGood;

//此控制器执行自动化脚本信息

class CrontabController extends BaseController {

  //自动确认收货
  public function actionOrderReceive(){
    $setting = Setting::findOne(1);
    $order_receive = $setting->order_receive ?: 7;
    $order_receive_timestep = $order_receive * 86400;
    $order_list = OrderInfo::find()->where(['order_type' => 1, 'state' => 2])
    ->andWhere(['<>', 'send_at', 0])
    ->andWhere(['<=', 'send_at', time() - $order_receive_timestep])
    ->all();
    if ($order_list) {
      foreach ($order_list as $order_info) {
        $order_info->state = 3;
        $order_info->receive_at = time();
        $order_info->save();
      }
    }
    return Re::data();
  }

  //订单自动完成
  public function actionOrderSuccess(){
    $setting = Setting::findOne(1);
    $order_success = $setting->order_success ?: 7; 
    $order_success_timestep = $order_success * 86400;
    $order_list = OrderInfo::find()
      ->where(['order_type' => 1, 'state' => 3])
      ->andWhere(['<>', 'receive_at', 0])
      ->andWhere(['<=', 'receive_at', time() - $order_success_timestep])->all();
    if ($order_list) {
      foreach ($order_list as $order_info) {
        $order_info->state = 4;
        $order_info->save();
      }
    }
    return Re::data();
  }

  //订单取消
	public function actionOrderCancel() {
    $order_list = OrderInfo::find()->where(['order_type' => 1, 'state' => 0])->andWhere(['<', 'created_at', time() - 7200])->all();
    if ($order_list) {
      foreach ($order_list as $order_info) {
        $order_info->state = 8;
        $order_info->save();
        $order_good_list = OrderInfoGood::find()->where(['order_id' => $order_info->id])->all();
        if ($order_good_list) {
          foreach ($order_good_list as $order_good_info) {
            $order_good_info->good->store += $order_good_info->num;
            $order_good_info->save();
          }
        }
      }
    }
		return Re::data();
	}
}
